#!/bin/bash

#checks a directory for changes against a hash and runs the
#program when a change is found.

if [ ! -a ~/.mp3watch ]
then
    touch ~/.mp3watch
fi

if [ -z "$1" ]
then
    echo "Error: No directory specified."
    exit 1
fi


while [ true ]
do
    if [[ `ls "$1" | (diff - ~/.mp3watch)` != '' ]]
    then
        #convert all flac files to mp3

        files=`find "$1" -iname "*.flac"`

        if [[ -z $files ]]
        then
            exit 0
        fi

        for f in "$files"
        do
            #make sure the file is still not increasing in size (being copied)
            so=`du "$f"`
            s=""


            while [[ "$s" != "$so" ]]
            do
                sleep 1
                so="$s"
                s=`du $f`
            done
            
            ffmpeg -i "$f" -ab 256k "$f.mp3"
            rename ".flac" "" "$f.mp3"
            rm "$f"
        done
        
        #update the diff file
        ls "$1" > ~/.mp3watch
    fi
    sleep 2
done

